/*
 * smart2DArray.h
 *
 *  Created on: 2011-09-02
 *      Author: pawel
 */

#ifndef SMART2DARRAY_H_
#define SMART2DARRAY_H_
#include<string.h>
#include <stdexcept>
/*
 * Template class implements 2 Dimensional array
 * if bad_alloc exception is thrown during creating
 * class frees all allocated memory
 */
template<class T>
class smart2DArray{
private:
	T **array;
	size_t rows;
	size_t cols;
public:
	smart2DArray(size_t rows,size_t cols);
	~smart2DArray();
	T** getPtr();
	void release();
};
template <class T>
smart2DArray<T>::smart2DArray(size_t rows,size_t cols)
:rows(rows),cols(cols)
{
	array = NULL;
	try{
	array = new T*[rows];
	for(size_t i=0;i<rows;i++){
			array[i] = NULL;
	}
	for(size_t i=0;i<rows;i++){
			array[i] = new T[cols];

	}
	}catch(std::bad_alloc& e){
		if(array !=NULL){
				for(size_t i=0;i<rows;i++){
					if(array[i]!=NULL){
						delete[] array[i];
						array[i]=NULL;
					}
				}
				delete[] array;
					array= NULL;
			}
		throw;
	}

}
template <class T>
smart2DArray<T>::~smart2DArray(){
	if(array !=NULL){
		for(size_t i=0;i<rows;i++){
			if(array[i] != NULL)
			delete[] array[i];
		}
		delete[] array;
	}

}
template <class T>
T** smart2DArray<T>::getPtr(){
	return array;
}
template <class T>
void smart2DArray<T>::release(){

			array = NULL;
}

#endif /* SMART2DARRAY_H_ */
